<template>
  <div class="container view-container">
    <div :contentScrollbar="true" class="search">
      <div class="searchFormRef">
        <div class="item">
          <div class="label">标注分类：</div>
          <el-input v-model="label"></el-input>
        </div>
        <div class="item">
          <div class="label">视频名称：</div>
          <el-input v-model="videoName"></el-input>
        </div>
        <div class="item">
          <div class="label2">生成日期：</div>
          <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </div>
      </div>
      <div class="btn">
        <el-button class="item" type="primary" @click="searchData">查询</el-button>
        <el-button class="item" type="primary" @click="resetSearch">重置</el-button>
      </div>
    </div>
    <div class="tableList">
      <div class="btn">
        <div class="left"></div>
        <el-button type="primary" style="margin: 5px 60px" @click="mutilRoadVideoMark(null)"> 多路视频播放 </el-button>
      </div>
      <div class="tablecontent">
        <BaseTable v-bind="tableProps" v-loading="loading"  :paginationData="paginationData" :tableData="tableData" ref="BaseTableRef"></BaseTable>
      </div>
      <div class="footer">
        <div class="BasePagination">
          <BasePagination :paginationData="paginationData" @paginationChange="searchData" />
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, unref, onActivated } from 'vue';
import router from '@/router';
import {
  getTextMarkInfoQuery,
  getTextMarkInfoQueryCount,
  selectVideoListByIds,
  deleteMark,
} from '@renderer/src/utils/ipc';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';

const paginationData = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

const value1 = ref();
const loading = ref(false);
const BaseTableRef = ref();
let savePath = '';
const videoName = ref('');
const label = ref('');

//正在导入的进程数据
let currentExport = [
  {
    row: null,
    cancelFuntion: () => {}, //用户取消下载
  },
];

const tableProps = reactive({
  tableColumns: [
    {
      prop: 'check',
      type: 'selection',
    },
    {
      type: 'index',
      width: 150,
      label: '序号',
    },
    {
      prop: 'label',
      label: '标注分类',
    },
    {
      prop: 'v_video_name',
      label: '视频名称',
    },
    {
      prop: 'startTimeDec',
      width: 120,
      label: '开始时间点',
    },
    {
      prop: 'endTimeDec',
      width: 120,
      label: '结束时间点',
    },
    {
      prop: 'create_time',
      label: '生成时间',
    },
    {
      prop: 'describe',
      label: '问题描述',
    },
    {
      prop: 'download_status',
      label: '下载状态',
      type: 'progress',
    },
    {
      label: '操作',
      width: 300,
      fixed: 'right',
      operaterList: [
        {
          name: '播放',
          operater: (item) => {
            videoMark(item.row);
          },
        },
        {
          type: 'progress',
          name: '导出标注',
          unname: '取消导出',
          prop: 'download_status',
          operater: (item) => {
            downLoadFile(item);
          },
        },
        {
          name: '删除',
          operater: (item) => {
            deleteRecord(item.row);
          },
        },
      ],
    },
  ],
});

const tableData: any = reactive([]);

const deleteRecord = (row) => {
  ElMessageBox.confirm('是否确定删除当前数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(async () => {
      await deleteItem(row);
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};

const deleteItem = async (row) => {
  await deleteMark({
    id: row.id,
    status: '1',
    type: row.type,
  });
  const item = tableData.find((item) => {
    if (row.id == item.id && row.type == item.type) {
      return item;
    }
  });
  if (item) {
    let index = tableData.indexOf(item);
    console.log(index);
    if (index != -1) {
      tableData.splice(index, 1);
    }
    console.log(tableData);
  }
};

onActivated(() => {
  searchData();
});

const getTimeDesc = (time) => {
  return time;
};
const getTimeDesc1 = (item) => {
  const time1 = dayjs(item.v_start_time);
  const time2 = dayjs(item.start_time);
  const diff = time2.diff(time1, 'seconds');
  return diff;
};
//查询数据
const searchData = async () => {
  try {
    tableData.length = 0;
    loading.value = true;
    let startT = value1.value ? value1.value[0] + ' 00:00:00' : '';
    let endT = value1.value ? value1.value[1] + ' 23:59:59' : '';
    let queryParams = {
      startTime: startT,
      endTime: endT,
      label: label.value,
      videoName: videoName.value,
      page: paginationData.pageSize,
      current: paginationData.pageSize * (paginationData.pageNum - 1),
    };
    console.log('aaaaaaaaaaa', startT, endT, queryParams);
    let rest = await getTextMarkInfoQuery(queryParams);
    console.log(rest);
    rest.map((item) => {
      tableData.push({
        ...item,
        startTimeDec: item.type == '1' ? getTimeDesc(item.start_time) : getTimeDesc1(item),
        endTimeDec: getTimeDesc(item.end_time),
        download_status: 0,
      });
    });
    let res = await getTextMarkInfoQueryCount(queryParams); //获取总记录数
    paginationData.total = res.count;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
};

//导出标注
const downLoadFile = async (item) => {
  if (currentExport.length > 0 && currentExport[0].row == null) {
    currentExport.length = 0;
  }
  if (item.row.download_status == 0 || item.row.download_status >= 100) {
    setTimeout(async () => {
      await exportData(item.row);
    }, 100);
  } else if (item.row.download_status > 0 && item.row.download_status < 100) {
    const itemStop = currentExport.find((itemIng) => {
      if (itemIng.row === item.row) {
        return itemIng;
      }
    });
    if (itemStop) {
      let index = currentExport.indexOf(itemStop);
      if (index !== -1) {
        item.row.download_status = 0;
        await currentExport[index].cancelFuntion();
        currentExport.splice(index, 1);
      }
    }
  }
};

interface fieldConfig {
  zhCn?: string;
  enName?: string;
}

const formatExportData = (dataList, headerConfigList) => {
  let restList: Array<Map<string, Object>> = new Array<Map<string, Object>>();
  for (let index = 0; index < dataList.length; index++) {
    const element = dataList[index];
    let Object: Map<string, Object> = new Map<string, Object>();
    headerConfigList.forEach((item) => {
      if (item.enName == 'index') {
        Object[item.zhCn] = index + 1;
      } else {
        Object[item.zhCn] = element[item.enName];
      }
    });
    restList.push(Object);
  }
  return restList;
};

const getHeaderConfigList = () => {
  let headerConfigList: Array<fieldConfig> = new Array<fieldConfig>();
  headerConfigList.push({ enName: 'index', zhCn: '序号' });
  headerConfigList.push({ enName: 'start_time', zhCn: '开始时间' });
  headerConfigList.push({ enName: 'end_time', zhCn: '结束时间' });
  headerConfigList.push({ enName: 'label', zhCn: '标注分类' });
  headerConfigList.push({ enName: 'describe', zhCn: '问题描述' });
  headerConfigList.push({ enName: 'create_time', zhCn: '生成时间' });
  return headerConfigList;
};

const exportData = async (row) => {
  //选择文件夹
  if (savePath == '') {
    savePath = await window.api.openDirectory();
    savePath = savePath ? savePath : '';
  }
  if (savePath !== '') {
    row.download_status = 0;
    let fileName = row.v_video_name.split('.')[0] + row.create_time.split(' ')[0].replaceAll('-', '');
    let dataList = [{ ...row }];
    let dataListNew = formatExportData(dataList, getHeaderConfigList());
    window.api.jsonToCsv(dataListNew, savePath, fileName + '.csv'); //下载csv 文件
    let source = row.save_path + `\\${row.v_video_name}`;
    const cancelFuntion = window.api.copyFileWithProgress(
      source,
      savePath + `\\${row.v_video_name}`,
      (transferred, progress) => {
        let current = parseInt(100.0 * (transferred / progress));
        if (row.download_status < current) {
          row.download_status = current;
          if (row.download_status >= 100) {
            const itemFinish = currentExport.find((itemIng) => {
              if (itemIng.row === row) return itemIng;
            });
            if (itemFinish) {
              let index = currentExport.indexOf(itemFinish);
              currentExport.splice(index, 1);
              ElMessage.success('下载完成');
            } else {
              row.download_status = 0;
            }
          }
        }
      },
    );
    currentExport.push({ row: row, cancelFuntion });
  } else {
    ElMessage.error('请选择保存路径');
  }
};

//视频标注
const videoMark = (row) => {
  mutilRoadVideoMark(row);
};

//多路视频标注
const mutilRoadVideoMark = async (row) => {
  let batchData: Array<Object> = new Array<Object>();
  if (row == null) {
    batchData = unref(BaseTableRef).tableRef.getSelectionRows();
    if (batchData.length <= 0) {
      ElMessage.error('未选择视频');
      return;
    }
  } else {
    batchData.push(row);
  }
  let v_ids: Array<string> = new Array<string>();
  //过滤掉相同文件，从数据库重新获取列表
  batchData.map((item) => {
    v_ids.push(item.v_id);
  });
  const Ids = [...new Set(v_ids)];
  let rest = await selectVideoListByIds({ ids: Ids.join() });
  let queryList = rest.map((item) => {
    return { ...item };
  });
  let json = JSON.stringify(queryList);
  void router.push({ path: '/textAnnotaion/textannotation', query: { params: json } });
};

//重置
const resetSearch = async () => {
  value1.value = null;
  label.value = '';
  videoName.value = '';
  searchData();
};
</script>
<style lang="less" scoped>
:deep(.el-table thead th) {
  font-weight: 500;
  font-size: 16px;
  color: #020f1b;
  font-style: normal;
}
.container {
  display: flex;
  flex-direction: column;
  padding: 6px;
  height: 100%;
  width: 100%;
  min-width: 650px;
  width: auto;
  .search {
    height: 100px;
    background-color: rgb(240, 242, 245);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .searchFormRef {
      display: flex;
      flex-direction: row;
      height: 50px;
      justify-content: center;
      align-items: center;
      .item {
        display: flex;
        flex-direction: row;
        justify-content: start;
        align-items: center;
        margin-left: 10px;
        .label {
          font-weight: 500;
          font-size: 16px;
          color: #020f1b;
          font-style: normal;
          margin-left: 10px;
          width: 150px;
        }
      }
    }
    .btn {
      flex: 1;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      .item {
        width: 100px;
      }
    }
  }
  .tableList {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    overflow: hidden;
    height: 100%;
    .btn {
      display: flex;
      justify-content: space-between;
      min-width: 580px;
      width: 100%;
      align-items: flex-end;
      border-bottom: solid rgb(240, 242, 245) 1px;
      .left {
        flex: 1;
      }
      .el-button {
        width: 120px;
      }
    }
    .tablecontent {
      flex: 1;
      width: 100%;
      position: relative; // table的直接父元素加position属性
      :deep(.el-table) {
        // table 加position属性
        position: absolute;
      }
    }
    .footer {
      height: 80px;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
      .BasePagination {
        // left: 50%;
        height: 100%;
      }
    }
  }
}
</style>
